package com.opencee.cloud.base.listener;

import cn.hutool.core.bean.BeanUtil;
import com.opencee.cloud.base.entity.BaseAccessLogsEntity;
import com.opencee.cloud.base.service.IBaseAccessLogsService;
import com.opencee.cloud.base.service.IpRegionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * API访问日志消息处理
 *
 * @author liuyadu
 */
@Component
@Slf4j
public class AccessLogsListener {

    @Autowired
    private IBaseAccessLogsService baseApiAccessLogsService;
    @Autowired
    private IpRegionService ipRegionService;
    /**
     * 接收访问日志
     *
     * @param map
     */
    @RabbitListener(queues = "api.gateway.access.log")
    public void accessLogsHandler(@Payload Map map) {
        try {
            if (map != null) {
                BaseAccessLogsEntity logs = BeanUtil.mapToBean(map, BaseAccessLogsEntity.class, true);
                if (logs != null) {
                    if (logs.getIp() != null) {
                        logs.setRegion(ipRegionService.getRegion(logs.getIp()));
                    }
                    baseApiAccessLogsService.save(logs);
                }
            }
        } catch (Exception e) {
            log.error("error:", e);
        }
    }
}
